<?php
namespace app\admin\controller\users;

use app\admin\controller\Auth;
use app\admin\controller\Paginate;
use app\common\model\Calculation;
use app\common\model\coin\CoinRuleRun;
use app\common\model\coin\CoinRuleRunTrade;
use app\common\model\order\OrderTake as OrderTakeModel;
use app\common\model\users\ProfitStatistics;
use mall\response\Response;
use think\facade\Request;
use think\facade\View;

class Profit extends Auth {


    // 设置应收手续费率
    private $serviceRate = 0.05;

    // 显示的小数点位数
    private $scaleShow = 4;

    /**
     * 获取保留的小数点位数
     * @return int
     */
    private function scale() {
        static $scale;
        if(empty($scale)) {
            $scale = (new CoinRuleRun())->scale;
        }
        return $scale;
    }


    /**
     * 统计概况
     * @return string
     */
    public function index() {

        // 获取数据
        $getListFunc = function(){
            $list = (new ProfitStatistics())->unionByDate( explode(' ',date(' Y-m Y-m-d')),0,['type','date','cost','profit','service_charge_deducted','reduce_fees']);
            $typeList = array_flip(ProfitStatistics::TYPE_LIST);
            $result = [];
            foreach($list as $value) {
                $result[$typeList[$value['type']]] = $value;
            }
            return $result;
        };
        $list = $getListFunc();
        $formatListFunc = function($key,$title = '') use($list){
            $details = array_key_exists($key,$list)?$list[$key]:[];
            $fields = [
                ['卖出成本','cost',''],
                ['盈利金额','profit',''],
                ['已收服务费','service_charge_deducted',''],
                ['节省手续费','reduce_fees',''],
            ];
            $result = [];
            foreach($fields as $field) {
                $value = array_key_exists($field[1],$details)?$details[$field[1]]:0;
                $result[] = [
                    'key'   => $field[0],
                    'value' => Calculation::trimZero($value,$this->scaleShow) . $field[2],
                ];
            }
            return [
                'title' => $title,
                'list'  => $result,
            ];
        };

        // 获取盈利统计数据
        $data = [
            $formatListFunc('DAY','今天盈利'),
            $formatListFunc('MONTH','本月盈利'),
            $formatListFunc('ALL','历史盈利'),
        ];
        return View::fetch('',[
            'data'  => $data
        ]);
    }


    /**
     * 月度盈利统计
     * @return strin
     */
    public function monthlyStatistics() {
        if(!Request::isAjax()){
            return View::fetch();
        }
        $month = Request::get("key.month");
        $beginTime = strtotime($month . '-01 00:00:00');
        if(date('Y-m',$beginTime) != $month) {
            $month = date('Y-m');
        }

        return $this->statistics($month);
        // 判断用户名搜索
        if($params['username']) {
            $where[] = ['username','like',$params['username'] . '%'];
        }

        $fields = [
            'user.id','user.username','user.local_amount','user.local_balance','user.has_service_charge','user.vip','user.vip_expire','user.create_time',
            'profit.profit','profit.service_charge','profit.service_charge_deducted'
        ];

        // 模型参数
        $model = (new Users())->alias('user')
            ->join('profit_statistics profit','profit.user_record=user.id','LEFT')
            ->where($where)->field($fields);
        // 获取列表数据
        $list = Paginate::getList($model);
        //返回结果
        return Response::returnArray("ok",0,$list['data'],$list['count']);
        echo $month;exit;
        $endTime =strtotime('+1 month',$beginTime) -1;
        $statisticsList = $this->statistics($beginTime,$endTime);
        return Response::returnArray("ok",0,$statisticsList,count($statisticsList));
    }


    /**
     * 日盈利统计
     * @return strin
     */
    public function dailyStatistics() {
        if(!Request::isAjax()){
            return View::fetch();
        }
        // 获取默认日期
        $getDefaultFunc = function(){
            $beginTime = strtotime(date('Y-m-d 00:00:00'));
            return [$beginTime,strtotime('+1 day',$beginTime) - 1];
        };
        $day = Request::get("key.day");
        $day = explode(' ~ ',trim($day));
        if(count($day) == 2) {
            list($beginTime,$endTime) = $day;
            $beginTime = strtotime($beginTime . ' 00:00:00');
            $endTime = strtotime($endTime . ' 00:00:00');

            if(date('Y-m-d',$beginTime) == $day[0] && date('Y-m-d',$endTime) == $day[1]) {
                $endTime =strtotime('+1 day',$endTime) -1;
            } else {
                list($beginTime,$endTime) = $getDefaultFunc();
            }
        } else {
            list($beginTime,$endTime) = $getDefaultFunc();
        }
        return $this->statistics([date('Y-m-d',$beginTime),date('Y-m-d',$endTime)]);
    }


    /**
     * 获取统计数据
     * @param $beginTime 开始时间
     * @param $endTime  结束时间
     * @param null $userId  指定用户ID
     * @param string $groupBy 分组类型
     * @return array
     */
    private function statistics($date) {

        // 获取查询参数
        $params = Paginate::getSearchParams('key',[
            'username'  => ['','str'],
        ]);
        $where[] = ['profit.type','=',ProfitStatistics::dateToType(is_array($date)?$date[0]:$date)];
        $where[] = ['profit.time_zone','=',ProfitStatistics::getTimezone(null,true)];
        if(is_array($date)) {
            $where[] = ['profit.date','between',$date];
        } else {
            $where[] = ['profit.date','=',$date];
        }

        $where[] = ['profit.user_id','>',0];
        // 判断用户名搜索
        if($params['username']) {
            $where[] = ['user.username','like',$params['username'] . '%'];
        }

        $fields = [
            'profit.*',
            'user.username'
        ];
        // 模型参数
        $model = (new ProfitStatistics())->alias('profit')
            ->join('users user','user.id=profit.user_id','LEFT')
            ->order(['profit.date'=>'desc','profit.profit'=>'desc'])
            ->where($where)->field($fields);
        // 获取列表数据
        $list = Paginate::getList($model);
        //返回结果
        return Response::returnArray("ok",0,$list['data'],$list['count']);

    }

}
